<template>
  <q-dialog v-model="isOpenComputed" persistent maximized class="filter-modal">
    <q-card class="filter-modal-card">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">展会筛选</div>
        <q-space />
        <div class="text-subtitle2">共 {{ totalRecords }} 条记录</div>
        <q-btn icon="close" flat round dense @click="closeModal" />
      </q-card-section>

      <q-card-section class="q-pt-md">
        <!-- Search input -->
        <q-input
          v-model="searchInput"
          dense
          outlined
          placeholder="输入关键词搜索"
          class="q-mb-md filter-search"
          clearable
        >
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>

        <!-- Filter content -->
        <div class="row filter-content">
          <!-- Continent Column -->
          <div class="col-3 filter-column">
            <div class="column-title">洲</div>
            <div class="column-content">
              <q-list separator>
                <q-item
                  v-for="continent in filteredContinents"
                  :key="continent"
                  clickable
                  :active="selectedContinent === continent"
                  @click="selectContinent(continent)"
                  active-class="bg-primary-1 text-primary"
                >
                  <q-item-section>
                    <q-item-label>{{ continent }}</q-item-label>
                  </q-item-section>
                  <q-item-section side v-if="continentCounts[continent]">
                    <q-chip size="sm" color="primary" text-color="white" class="count-chip">
                      {{ continentCounts[continent] }}
                    </q-chip>
                  </q-item-section>
                </q-item>
              </q-list>
            </div>
          </div>

          <!-- Country Column -->
          <div class="col-3 filter-column">
            <div class="column-title">国家</div>
            <div class="column-content">
              <q-list separator>
                <q-item
                  v-for="country in filteredCountries"
                  :key="country"
                  clickable
                  :active="selectedCountry === country"
                  @click="selectCountry(country)"
                  active-class="bg-primary-1 text-primary"
                >
                  <q-item-section>
                    <q-item-label>{{ country }}</q-item-label>
                  </q-item-section>
                  <q-item-section side v-if="countryCounts[country]">
                    <q-chip size="sm" color="primary" text-color="white" class="count-chip">
                      {{ countryCounts[country] }}
                    </q-chip>
                  </q-item-section>
                </q-item>
              </q-list>
            </div>
          </div>

          <!-- City Column -->
          <div class="col-3 filter-column">
            <div class="column-title">城市</div>
            <div class="column-content">
              <q-list separator>
                <q-item
                  v-for="city in filteredCities"
                  :key="city"
                  clickable
                  :active="selectedCity === city"
                  @click="selectCity(city)"
                  active-class="bg-primary-1 text-primary"
                >
                  <q-item-section>
                    <q-item-label>{{ city }}</q-item-label>
                  </q-item-section>
                  <q-item-section side v-if="cityCounts[city]">
                    <q-chip size="sm" color="primary" text-color="white" class="count-chip">
                      {{ cityCounts[city] }}
                    </q-chip>
                  </q-item-section>
                </q-item>
              </q-list>
            </div>
          </div>

          <!-- Industry Column -->
          <div class="col-3 filter-column">
            <div class="column-title">行业</div>
            <div class="column-content">
              <q-list separator>
                <q-item
                  v-for="industry in filteredIndustries"
                  :key="industry"
                  clickable
                  :active="selectedIndustry === industry"
                  @click="selectIndustry(industry)"
                  active-class="bg-primary-1 text-primary"
                >
                  <q-item-section>
                    <q-item-label>{{ industry }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </div>
          </div>
        </div>
      </q-card-section>

      <!-- Additional filters row -->
      <q-card-section class="q-pt-none">
        <div class="row q-col-gutter-md additional-filters">
          <!-- Supply Chain Filter -->
          <div class="col-3">
            <q-select
              v-model="isSupplyChain"
              :options="[
                { label: '全部', value: '' },
                { label: '是', value: '是' },
                { label: '否', value: '否' }
              ]"
              label="是否供应链重点展会"
              outlined
              dense
              emit-value
              map-options
            >
              <template v-slot:prepend>
                <q-icon name="inventory" color="primary" size="xs" />
              </template>
            </q-select>
          </div>

          <!-- CCPIT Filter -->
          <div class="col-3">
            <q-select
              v-model="isCcpit"
              :options="[
                { label: '全部', value: '' },
                { label: '是', value: '是' },
                { label: '否', value: '否' }
              ]"
              label="是否CCPIT展会"
              outlined
              dense
              emit-value
              map-options
            >
              <template v-slot:prepend>
                <q-icon name="verified" color="primary" size="xs" />
              </template>
            </q-select>
          </div>

          <!-- Holding Time Filter -->
          <div class="col-3">
            <q-select
              v-model="holdingTime"
              :options="['全部', '本月', '下月', '本季度', '下季度']"
              label="举办时间"
              outlined
              dense
            >
              <template v-slot:prepend>
                <q-icon name="calendar_month" color="primary" size="xs" />
              </template>
            </q-select>
          </div>

          <!-- AI Mismatch Filter -->
          <div class="col-3">
            <q-checkbox 
              v-model="isIndustryMismatch"
              label="仅显示与AI不一致的展会"
              dense
            />
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="bg-white q-py-md">
        <q-btn flat label="重置筛选" color="grey-7" @click="resetFilters" />
        <q-btn flat label="取消" color="grey-7" @click="closeModal" />
        <q-btn unelevated label="应用筛选" color="primary" @click="applyFilters" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getRegionMap, getIndustryMap } from 'src/api/exhibition';

const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  totalRecords: {
    type: Number,
    default: 0
  },
  industryOptions: {
    type: Array,
    default: () => []
  },
  continentCounts: {
    type: Object,
    default: () => ({})
  },
  countryCounts: {
    type: Object,
    default: () => ({})
  },
  cityCounts: {
    type: Object,
    default: () => ({})
  },
  industryCounts: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:isOpen', 'apply-filters']);

// Computed property for v-model binding
const isOpenComputed = computed({
  get: () => props.isOpen,
  set: (value) => emit('update:isOpen', value)
});

// Function to close the modal
const closeModal = () => {
  emit('update:isOpen', false);
};

// Search and filter state
const searchInput = ref('');
const regionMap = ref({});
const selectedContinent = ref('');
const selectedCountry = ref('');
const selectedCity = ref('');
const selectedIndustry = ref('');

// Additional filter state
const isSupplyChain = ref('');
const isCcpit = ref('');
const holdingTime = ref('全部');
const isIndustryMismatch = ref(false);

// Counts for each filter option - use props if available, otherwise empty objects
const continentCounts = computed(() => Object.keys(props.continentCounts).length ? props.continentCounts : continentCountsLocal.value);
const countryCounts = computed(() => Object.keys(props.countryCounts).length ? props.countryCounts : countryCountsLocal.value);
const cityCounts = computed(() => Object.keys(props.cityCounts).length ? props.cityCounts : cityCountsLocal.value);

// Local state for counts (used as fallback)
const continentCountsLocal = ref({});
const countryCountsLocal = ref({});
const cityCountsLocal = ref({});
const industryCountsLocal = ref({});

// Get all continents from regionMap
const allContinents = computed(() => Object.keys(regionMap.value));

// Filter continents based on search input
const filteredContinents = computed(() => {
  if (!searchInput.value) return allContinents.value;
  
  return allContinents.value.filter(continent => 
    continent.toLowerCase().includes(searchInput.value.toLowerCase())
  );
});

// Get all countries based on selected continent
const allCountries = computed(() => {
  if (!selectedContinent.value) {
    // If no continent is selected, get all countries from all continents
    return Object.values(regionMap.value).reduce((acc, continentData) => {
      return [...acc, ...Object.keys(continentData)];
    }, []);
  }
  return Object.keys(regionMap.value[selectedContinent.value] || {});
});

// Filter countries based on search input
const filteredCountries = computed(() => {
  if (!searchInput.value) return allCountries.value;
  
  return allCountries.value.filter(country => 
    country.toLowerCase().includes(searchInput.value.toLowerCase())
  );
});

// Get all cities based on selected continent and country
const allCities = computed(() => {
  if (!selectedContinent.value) {
    // If no continent is selected, get all cities from all countries
    return Object.values(regionMap.value).reduce((acc, continentData) => {
      return [...acc, ...Object.values(continentData).reduce((cities, countryData) => {
        return [...cities, ...countryData];
      }, [])];
    }, []);
  }
  
  if (!selectedCountry.value) {
    // If continent is selected but no country, get all cities from that continent
    return Object.values(regionMap.value[selectedContinent.value] || {}).reduce((acc, cities) => {
      return [...acc, ...cities];
    }, []);
  }
  
  return regionMap.value[selectedContinent.value]?.[selectedCountry.value] || [];
});

// Filter cities based on search input
const filteredCities = computed(() => {
  if (!searchInput.value) return allCities.value;
  
  return allCities.value.filter(city => 
    city.toLowerCase().includes(searchInput.value.toLowerCase())
  );
});

// 添加行业数据状态
const industries = ref([]);

// 修改 filteredIndustries 计算属性
const filteredIndustries = computed(() => {
  if (!searchInput.value) return industries.value;
  
  return industries.value.filter(industry => 
    industry.toLowerCase().includes(searchInput.value.toLowerCase())
  );
});

// Functions to handle selections
const selectContinent = (continent) => {
  if (selectedContinent.value === continent) {
    selectedContinent.value = '';
  } else {
    selectedContinent.value = continent;
  }
  selectedCountry.value = '';
  selectedCity.value = '';
};

const selectCountry = (country) => {
  if (selectedCountry.value === country) {
    selectedCountry.value = '';
  } else {
    selectedCountry.value = country;
  }
  selectedCity.value = '';
};

const selectCity = (city) => {
  if (selectedCity.value === city) {
    selectedCity.value = '';
  } else {
    selectedCity.value = city;
  }
};

const selectIndustry = (industry) => {
  if (selectedIndustry.value === industry) {
    selectedIndustry.value = '';
  } else {
    selectedIndustry.value = industry;
  }
};

// Reset all filters
const resetFilters = () => {
  searchInput.value = '';
  selectedContinent.value = '';
  selectedCountry.value = '';
  selectedCity.value = '';
  selectedIndustry.value = '';
  
  // Reset additional filters
  isSupplyChain.value = '';
  isCcpit.value = '';
  holdingTime.value = '全部';
  isIndustryMismatch.value = false;
};

// Apply filters and close modal
const applyFilters = () => {
  emit('apply-filters', {
    continent: selectedContinent.value,
    country: selectedCountry.value,
    city: selectedCity.value,
    industry: selectedIndustry.value,
    
    // Include additional filters
    is_supply_chain: isSupplyChain.value,
    is_ccpit: isCcpit.value,
    holding_time: holdingTime.value !== '全部' ? holdingTime.value : null,
    is_industry_mismatch: isIndustryMismatch.value
  });
  emit('update:isOpen', false);
};

// 修改 onMounted 钩子
onMounted(async () => {
  try {
    // 获取地区数据
    const regionRes = await getRegionMap();
    regionMap.value = regionRes.data;
    
    // 获取行业数据
    const industryRes = await getIndustryMap();
    industries.value = industryRes.data;
    
    // Generate random counts only if props don't provide them
    if (Object.keys(props.continentCounts).length === 0) {
      for (const continent of allContinents.value) {
        continentCountsLocal.value[continent] = Math.floor(Math.random() * 100) + 1;
      }
      
      for (const country of allCountries.value) {
        countryCountsLocal.value[country] = Math.floor(Math.random() * 50) + 1;
      }
      
      for (const city of allCities.value) {
        cityCountsLocal.value[city] = Math.floor(Math.random() * 20) + 1;
      }
      
      for (const industry of industries.value) {
        industryCountsLocal.value[industry] = Math.floor(Math.random() * 30) + 1;
      }
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
});
</script>

<style lang="scss" scoped>
.filter-modal {
  &-card {
    max-width: 90vw;
    max-height: 90vh;
    width: 90vw;
    border-radius: 8px;
  }
  
  .filter-search {
    max-width: 400px;
  }
  
  .filter-content {
    height: calc(80vh - 150px);
    border: 1px solid #e0e0e0;
    border-radius: 4px;
  }
  
  .filter-column {
    height: 100%;
    border-right: 1px solid #e0e0e0;
    display: flex;
    flex-direction: column;
    
    &:last-child {
      border-right: none;
    }
    
    .column-title {
      padding: 12px;
      font-weight: 500;
      background-color: #f5f5f5;
      border-bottom: 1px solid #e0e0e0;
    }
    
    .column-content {
      flex: 1;
      overflow-y: auto;
    }
  }
  
  .q-item {
    min-height: 40px;
    
    &.q-item--active {
      font-weight: 500;
    }
  }
  
  .count-chip {
    min-width: 24px;
    height: 20px;
    padding: 0 4px;
    font-size: 11px;
  }
  
  .bg-primary-1 {
    background-color: rgba(25, 118, 210, 0.1);
  }
}
</style> 